<template>
  <Modal v-model="modal" :title="title" width='1000' class="box">
    <div class="freight-modal  scroll">
      <Form :label-width="50" :rules="rule" ref="form" class="pb" :model="form">
        <!-- <Row class="pr">
          <Col span="12">
            <FormItem >
              <div class="font-red">提示：如只有默认运费，则所有经销商都按默认运费收取运费</div>
            </FormItem>
          </Col>
        </Row> -->
        <Row class="pr">
          <Col span="12">
            <FormItem label="标题" prop="title">
              <Input v-model="form.title" :disabled="isView" maxlength="12"/>
            </FormItem>
          </Col>
        </Row>
        <Row>
            <Col span="12">
              <FormItem label="描述">
                <Input
                  v-model="form.depiction"
                  type="textarea"
                  :autosize="{minRows: 2,maxRows: 5}"
                  placeholder="请填写描述,最多50个字"
                  maxlength="50">
                />
              </FormItem>
            </Col>
        </Row>
      </Form>
      <!-- 默认运费 -->
      <!-- <div class="line"><span class="font-red">* </span>默认运费 <InputNumber :disabled="isView" :max="999" :min="1" v-model="form.defaultNum"></InputNumber>条内 <InputNumber :max="999" :min="1" :disabled="isView" v-model="form.defaultFee"></InputNumber>元，每加1条加 <InputNumber :disabled="isView" :max="999" :min="1" v-model="form.extraFee"></InputNumber>元</div> -->
      <table cellspacing="0" class="table">
        <thead>
          <tr>
            <th v-for="item in list.columns" :key="item.id" :width="item.width">{{item.title}}</th>
          </tr>
        </thead>
        <tbody v-for="(item, index) in viewData" :key="item.id">
          <tr >
            <td width="200">
              <div class="pt e2">{{item.distributorNames.join(',')}}</div>
              <div ><Button class="mb"  type="primary" size="small" v-if="!isView" @click="onEditDis(item, index)">编辑</Button></div>
              <div><Button  class="mb"  type="primary" size="small" v-if="isView" @click="onViewDis(item, index)">查看</Button></div>
            </td>
            <td><InputNumber :disabled="isView" :max="999" :min="1" v-model="item.defaultNum"></InputNumber></td>
            <td class="cursor-title"><InputNumber  :disabled="isView" :max="999" :min="1" v-model="item.defaultFee"></InputNumber></td>
            <td><InputNumber :disabled="true" :max="999" :min="1" v-model="value1"></InputNumber></td>
            <!-- 退货价 -->
            <td>
              <InputNumber :max="999" :disabled="isView" :min="0" v-model="item.extraFee" ></InputNumber>
            </td>
            <td>
              <Button type="primary" size="small" v-if="viewData.length >= 2" :disabled="isView" @click="onDeleteSet(index)">删除</Button>
            </td>
          </tr>
        </tbody>
      </table>
      <Button class="info" :disabled="isView"  type="primary" size="small" @click="onAddSet(item)">为指定经销商设置运费，批量操作</Button>
      <!-- 免运费 -->
      <div class="mb mt"><Checkbox @on-change="onSetOpenFree" :disabled="isView" v-model="form.isOpenFree">免运费条件</Checkbox></div>
      <!-- <div class="line" v-if="form.isOpenFree"><span class="font-red">*</span> 默认满 <InputNumber :disabled="isView" :max="999" :min="1" v-model="form.freeNum"></InputNumber>条免费</div> -->
      <table cellspacing="0" v-if="form.isOpenFree" class="table">
        <thead>
          <tr>
            <th v-for="item in list.columns1" :key="item.id" :width="item.width">{{item.title}}</th>
          </tr>
        </thead>
        <tbody v-for="(item, index) in viewData1" :key="item.id">
          <tr>
            <td width="200">
              <div class="pt e2">{{item.distributorNames.join(',') }}</div>
              <div><Button class="mb"  type="primary" size="small" v-show="!isView" @click="onEditDis(item, index, '1')">编辑</Button></div>
              <div><Button class="mb"   type="primary" size="small" v-show="isView" @click="onViewDis(item, index)">查看</Button></div>
            </td>
            <!-- 退货价 -->
            <td>
              <InputNumber class="w60" :min="1" :max="999" :disabled="isView" style="width:60px;"   v-model="item.freeNum" ></InputNumber>
            </td>
            <td>
              <Button  type="primary" size="small" :disabled="isView" @click="onDeleteLine(index)">删除</Button>
            </td>
          </tr>
        </tbody>
      </table>
      <Button class="info" v-if="form.isOpenFree" :disabled="isView"  type="primary" size="small" @click="onAddLine(item)">添加一行</Button>
    </div>
    <transferItem ref="transfer" @complete="complete"></transferItem>
    <ViewItem ref="view"></ViewItem>
    <Loader :status="status" @refresh="onSearchBtnClick"></Loader>
    <div slot="footer">
        <Button @click="modal = false" size="large" type="text" v-if="step === 1">取消</Button>
        <Button @click="onSave" :loading='confrimLoading' type="primary" size="large" :disabled="isView" v-if="step === 1">确认</Button>
        <Button :disabled='allBtnLoading' :loading='selBtnLoading' @click="clearSelected" type="info" size="large" v-if="step === 2">选中规格库存清零</Button>
        <Button :disabled='selBtnLoading' :loading='allBtnLoading' @click="clearAll" type="warning" size="large" v-if="step === 2">当前页规格库存清零</Button>
    </div>
</Modal>
</template>
<script>
import SelectList from '@/components/SelectList';
import listData from './EditItemData';
import transferItem from './transferItem';
import ViewItem from './ViewItem'
export default {
  components: {
    SelectList,
    transferItem,
    ViewItem
  },
  computed: {
    title() {
      return this.step === 1 ? '新增运费模板' : '商品运费模板'
    }
  },
  data() {
    return {
      id: null,
      modal: false,
      options: {
        tableHeight: 200
      },
      form: {
        title: '',
        defaultNum: '',
        defaultFee: '',
        extraFee: '',
        isOpenFree: '',
        freeNum: '',
        depiction: '' 
      },
      rule: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }]
      },
      status: 'pass',
      list: listData,
      // viewData: [],
      // viewData1: [],
      viewData: [{
        defaultFee: '', // 首费
        defaultNum: '', // 首条数
        distributorIds: [], // 经销商
        distributorNames: [],
        extraFee: '', // 续费
        freightType: '0',
        distributorDTOS: []
      }],
      viewData1: [{
        freeNum: '',
        distributorIds: [], // 经销商,
        distributorNames: [],
        freightType: '1',
        distributorDTOS: []
      }],
      isView: false,
      resignBrand: '',
      brand: '',
      loading: false,
      departmentTree: [],
      value: [],
      step: 1,
      distributorId: '',
      distributorContractId: '',
      rebateMonth: '',
      selBtnLoading: false,
      allBtnLoading: false,
      confrimLoading: false,
      selectedRebateList: []
    };
  },
  mounted() {

  },
  methods: {
    onSetOpenFree() {
    },
    onViewDis(row) {
      this.$refs.view.open(row)
    },
    onAddSet () {
      this.viewData.push({
        defaultFee: '', // 首费
        defaultNum: '', // 首条数
        distributorIds: [], // 经销商
        extraFee: '', // 续费
        freightType: '0',
        distributorNames: [],
        distributorDTOS: []
      })
    },
    onAddLine () {
      this.viewData1.push({
        freeNum: '',
        distributorIds: [], // 经销商
        freightType: '1',
        distributorNames: [],
        distributorDTOS: []
      })
    },
    complete(row) {
      let index = 'viewData'
      if (row.type == 1) index = 'viewData1'
      this[index][row.index].distributorIds = row.data.map(item => {
        return item.id
      })
      this[index][row.index].distributorNames = row.data.map(item => {
        return item.distributorName
      })
      this[index][row.index].distributorDTOS =  row.data.map(item => {
        return {
          distributorName: item.distributorName,
          id: item.id,
          distributorId: item.id
        }
      })
    },
    onDeleteSet(index) {
      this.$Modal.confirm({
        title: "提醒",
        content: `确认要删除第${index + 1}条吗？`,
        onOk: () => {
          this.viewData.splice(index, 1)
        }
      });
    },
    onDeleteLine(index) {
      this.$Modal.confirm({
        title: "提醒",
        content: `确认要删除第${index + 1}条吗？`,
        onOk: () => {
          this.viewData1.splice(index, 1)
        }
      });
    },
    open(row) {
      this.modal = true
      if (row) {
        this.isView = true
        this.getData(row)
      } else {
        this.isView = false
        this.id = null
        this.viewData= [{
          defaultFee: '', // 首费
          defaultNum: '', // 首条数
          distributorIds: [], // 经销商
          extraFee: '', // 续费
          distributorNames: [],
          freightType: '0',
          distributorDTOS: []
        }]
        this.viewData1 = [{
          freeNum: '',
          distributorIds: [], // 经销商
          distributorNames: [],
          freightType: '1',
          distributorDTOS: []
        }]
        this.form = {
          title: '',
          defaultNum: '',
          defaultFee: '',
          extraFee: '',
          isOpenFree: false,
          freeNum: ''
        }
      }
    },
    openEdit(row) {
      this.modal = true
      this.isView = false
      this.getData(row)
      this.id = row.id
    },
    onPageChange(number) {
      this.list.currentPage = number;
      this.getData();
    },
    onPageSizeChange(pageSize) {
      this.list.currentPage = 1;
      this.list.pageSize = pageSize;
      this.getData();
    },
    setProp() {
      // 首费
      let text = ''
      // if (!this.form.defaultFee) {
      //   text = '首费不能为空'
      // } else if (!this.form.defaultNum) {
      //   text = '首条数不能为空'
      // } else if (!this.form.extraFee) {
      //   text = "续费不能为空"
      // } else if (this.form.isOpenFree && !this.form.freeNum) {
      //   text = '免费条数不能为空'
      // } else 
      if (this.viewData.length) {
        this.viewData.forEach(item => {
          for(var key in  item) {
            if (!item[key] && item[key] !==0 ) {
              text = '请把地区运费的设置都填全'
            }
          }
        })
      }
      if (this.form.isOpenFree && this.viewData1.length) {
        this.viewData1.forEach(item => {
          for(var key in  item) {
            if (!item[key]) {
              text = '请完善免运费条件'
            }
          }
        })
      }
      if (this.viewData.length) {
        this.viewData.forEach(item => {
          if (!item.distributorIds.length) {
            text = '请编辑地区运费设置的经销商'
          }
        })
      } 
      if (this.form.isOpenFree && this.viewData1.length) {
        this.viewData1.forEach(item => {
          if (!item.distributorIds.length) {
            text = '请编辑免运费设置的经销商'
          }
        })  
      } 
      return text
    },
    onSave () {
      let url = '/freight/setting/save'
      if (this.id) url = '/freight/setting/update'
      let param = {
        title: this.form.title,
        // defaultFee: this.form.defaultFee,
        // defaultNum: this.form.defaultNum,
        // extraFee: this.form.extraFee,
        depiction: this.form.depiction,
        isOpenFree: this.form.isOpenFree,
        freightTemplateItemDTOS: [
          ...this.viewData
        ]
      } 
      if (this.form.isOpenFree) {
        // param.freeNum = this.form.freeNum
        param.freightTemplateItemDTOS.push(...this.viewData1)
      }
      // param.freightTemplateItemDTOS.forEach(item =>{
        //   item.distributorIds = this.$refs.transfer.distribListed.map(item => {
          //     return item.distributorId
      //   })
      // })
      let error = this.setProp()
      if (error) {
        this.$Notice.error({
          title: error
        });
        return
      }
      if (this.id) param.id = this.id
       this.$refs.form.validate(valid => {
         if (valid) {
           this.status = 'loading'
           this.$jsonPost(url, param).then(res => {
             this.modal = false
             this.status = 'pass'
             let text = "新增成功"
             if (this.id) text = "编辑成功"
             this.$Notice.success({
               title: text
             });
             this.$emit('complete')
           }).catch(res => {
             this.status = 'pass'
           })
         }
       })
    },
    onEditDis(row, index) {
      this.$refs.transfer.editDistr(row.distributorDTOS, index, row.freightType)
    },
    getData(row) {
      this.status = 'loading'
      return this.$ajaxGet(`/freight/setting/detail`, {
        id: row.id
      }).then(res => {
        this.form = res
        this.status = 'pass'
        this.viewData = res.freightTemplateItemDTOS.filter(item => {return item.freightType == 0}).map(item=> {
          return {
            defaultFee: item.defaultFee, // 首费
            defaultNum: item.defaultNum, // 首条数
            distributorIds: item.distributorIds, // 经销商
            extraFee: item.extraFee, // 续费
            freightType: '0',
            distributorDTOS: item.distributorDTOS,
            distributorNames: item.distributorDTOS.map(item => {
              return item.distributorName
            })
          }
        })
        this.viewData1 = res.freightTemplateItemDTOS.filter(item => {return item.freightType == 1}).map(item => {
          return {
            freeNum: item.freeNum,
            distributorIds: item.distributorIds, // 经销商
            freightType: '1',
            distributorDTOS: item.distributorDTOS,
            distributorNames: item.distributorDTOS.map(item => {
              return item.distributorName
            })
          }
        })
      })
    },
    clearSelected() {
      if (!this.selectedRebateList.length) {
        this.$Message.info('请先选择商品')
        return
      }
      this.selBtnLoading = true
      this.rebate(this.selectedRebateList)
    },
    clearAll() {
      this.allBtnLoading = true
      this.rebate(this.list.data.map(item => item.id))
    },
    rebate(list) {
      let m = new Date(this.rebateMonth).getMonth() + 1
      this.$jsonPost('/distributorInventory/savePcd', {
        distributorId: this.distributorId,
        rebateMonth: m,
        tiredList: list
      }).then(res => {
        this.closeModal()
        this.$Message.success('操作成功')
        this.selBtnLoading = false
        this.allBtnLoading = false
      }).catch(() => {
        this.selBtnLoading = false
        this.allBtnLoading = false
      })
    },
    openModal() {
      this.step = 1
      this.modal = true;
      this.getDptTree()
    },
    closeModal() {
      this.modal = false;
    },
  }
}
</script>

